<?php
class RM_User_EnhancedCalendarController extends RM_Controller
{
    public function showAction(){
        ob_clean();
        $unitID = $this->_getParam('unit_id', null);
        $unitModel = new RM_Units();
        $unit = $unitModel->get($unitID);

        $json =  $this->_getdata($unitID);

        $this->view->calendardata = $json;
        $this->view->unit_id = $unitID;
        $this->view->unit = $unit;
        echo $this->view->render('EnhancedCalendar/calendar.phtml');
        die();
    }

    public function getdataJsonAction(){
        $unitID = $this->_getParam('unit_id', null);

        $json = $this->_getdata($unitID);

        echo $json;
        die();
    }

    private function _getdata($unitID){

        ob_clean();

        $unitModel = new RM_Units();
        $unit = $unitModel->get($unitID);
        $reservationModel = new RM_Reservations();
        $reservations = $reservationModel->fetchAllForUnitCalendar($unit);
         
        $jsonDisabledPeriods = array();
        $config = new RM_Config();
        $json = '{"evts": [';
        foreach ($reservations as $period) {
            $json .= '{';
            $json .= '"title":"'. $this->_translate->_('User.EnhancedCalendar', 'NotAvailable') .'",';
            $json .= '"cid":"1",';
            $json .= '"start": RM.Common.ConvertToDate("'.$config->convertDates($period->start_datetime, RM_Config::JS_DATEFORMAT, RM_Config::MYSQL_DATEFORMAT).'"),';
            $json .= '"end": RM.Common.ConvertToDate("'.$config->convertDates($period->end_datetime, RM_Config::JS_DATEFORMAT, RM_Config::MYSQL_DATEFORMAT).'")';
            $json .= '},';
        }

        // current criteria
        $criteria = RM_Reservation_Manager::getInstance()->getCriteria();
        if (@$criteria->start_datetime && @$criteria->end_datetime) {
            // add the criteria to the periods
            $json .= '{';
            $json .= '"title":"'. $this->_translate->_('User.EnhancedCalendar', 'YourSelection') .'",';
            $json .= '"cid":"2",';
            $json .= '"hidden": true,';
            $json .= '"start": RM.Common.ConvertToDate("'.$config->convertDates($criteria->start_datetime, RM_Config::JS_DATEFORMAT, RM_Config::MYSQL_DATEFORMAT).'"),';
            $json .= '"end": RM.Common.ConvertToDate("'.$config->convertDates($criteria->end_datetime, RM_Config::JS_DATEFORMAT, RM_Config::MYSQL_DATEFORMAT).'")';
            $json .= '},';
        }
        $json = trim($json,",");
        $json .= ']}';

        return $json;
    }

    public function readJsonAction(){}
    public function updateJsonAction(){}
    public function createJsonAction(){}
    public function deleteJsonAction(){}
}